var appid = "wx00b2e3c441296c24";
var appsecret = "31fe10e23ebf87e46003f12cf2af46e0";
var access_token;
var ticket;
var sign;

getAccessToken();
window.setInterval(clearTicket, 7200000); 
var clearTicket = function(){
    getAccessToken();
};

function getAccessToken(){
	console.log(new Date());
	var options = {
		hostname : "api.weixin.qq.com",
		path : "/cgi-bin/token?grant_type=client_credential&appid=" + appid + '&secret=' + appsecret
	};
	//根据options获取信息
	var req = https.get(options,function(res){
		var bodyChunks = '';
		res.on('data',function(chunk){
			bodyChunks += chunk;
		});
		res.on('end',function(){
			//解析数据
			var body = JSON.parse(bodyChunks);
			if(body.access_token){
				access_token = body.access_token;
				// saveAccessToken(access_token);
				apiTicket(access_token);
			}else{
				console.dir(body);
			}
		});
	});

	req.on('error',function(e){
		console.log('Error: ' + e.message);
	});
}

/**
 * [apiTicket 获取apiTicket]
 * @param  access_token
 */
function apiTicket(access_token){
	console.log("test: "+access_token);
	var options = {
		hostname : "api.weixin.qq.com",
		path : "/cgi-bin/ticket/getticket?access_token=" + access_token + '&type=jsapi'
	};
	var req = https.get(options,function(res){
		var bodyChunks = '';
		res.on('data',function(chunk){
			bodyChunks += chunk;
		});
		res.on('end',function(){
			var body = JSON.parse(bodyChunks);
			if(body.ticket){
                ticket = body.ticket;
                sign=sign(ticket,);
			}
		});
	});

	req.on('error',function(e){
		console.log('Error: ' + e.message);
	});
}